<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 把tp里查询出的对象转换成数组
 *
 * @param $object       对象数据
 * @return bool|mixed
 */
function tp_object_array($object)
{
    if (!is_object($object)) {
        return false;
    }
    return json_decode(json_encode($object),true);
}

/**
 * 获取客户端IP地址
 *
 * @param bool $adv 是否进行高级模式获取（有可能被伪装）
 * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($adv = true, $type = 0)
{
    $type       =  $type ? 1 : 0;
    static $ip  =  NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 整理树形菜单
 *
 * @param $data         菜单数组
 * @param int $pId      父id，默认0
 * @return array|string
 */
function get_tree($data, $pId = 0)
{
    $tree = [];
    foreach ($data as $k => $v) {
        if ($v['parentid'] == $pId && $v['display'] == 1) {
            // 保存到子菜单
            $v['submenu'] = get_tree($data, $v['id']);
            $tree[] = $v;
            // unset($data[$k]);
        }
    }
    return $tree;
}

/*
 * 精确时间间隔函数
 * $time 发布时间 如 1356973323
 * $str 输出格式 如 Y-m-d H:i:s
 * 半年的秒数为15552000，1年为31104000，此处用半年的时间
 */
function from_time($time, $str = 'y-m-d H:i')
{
    if (!is_int($time)) {
        $time = strtotime($time);
    }
    isset($str) ? $str : $str='m-d H:i';

    // 一天的秒数
    $day = 60*60*24;
    // 两天的秒数
    $pday = 60*60*24*2;
    // 三天的秒数
    $qday = 60*60*24*3;

    $way = time() - $time;
    $r = '';
    if ($way < 60) {
        $r = '刚刚';
    } elseif ($way >= 60 && $way < 60*60) {
        $r = floor($way/60).'分钟前';
    } elseif ($way >= 60*60 && $way < $day) {
        $r = floor($way/3600).'小时前';
    } elseif ($way >= $day && $way < $pday) {
        $r = '昨天 '.date('H:i', $time);
    } elseif ($way >= $pday && $way < $qday) {
        $r = '前天 '.date('H:i', $time);
    } else {
        $r = date($str, $time);
    }
    return $r;
}

/**
 * 验证字符串长度，一个字母和汉字都是一个长度计算
 * @param string $str       字符串
 * @param int $max_length   最大长度
 * @param int $min_length   最小长度
 * @param string $unicode   字符编码，默认utf-8
 * @return bool
 */
function validate_zh_leng($str = '', $max_length = 10, $min_length = 0, $unicode = 'utf-8')
{
    if (!isset($str) || $str == '') {
        return false;
    }
    if (mb_strlen($str, $unicode) > $max_length || mb_strlen($str, $unicode) < $min_length) {
        return false;
    }
    return true;
}

/**
 * 移除xss攻击
 * @param string $val       字符串
 * @return mixed|string
 */
function remove_xss($val = '')
{
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search  = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra  = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}

/**
 * 自定义LOG,base目录为data/log/,按自定义目录，按天分割存储.
 * @param string $msg           内容
 * @param string $fileDir       自定义文件目录
 * @param string $file_type
 * @return bool
 */
function printLog($msg = '', $fileDir = '', $file_type = 'c')
{
    if (empty($fileDir)) {
        $fileDir = date('Y-m-d');
    }
    $baseDir = ROOT_PATH . 'data/log/' . $fileDir . "/";
    if ($file_type == 'c') {
        $baseDir = ROOT_PATH . 'data/log/' . $fileDir . "/" . date('Ym') . '/';
    }
    if (!file_exists($baseDir)) {
        $res = mkdir($baseDir, 0777, true);
        if (!$res) {
            return false;
        }
    }
    if ($file_type == 'c') {
        $baseDir = $baseDir . date('d') . '.log';
    } else {
        $baseDir = $baseDir . date('Y') . '_'.date('m') . '_' . date('d') . '.log';
    }

    $request = request();
    $ip  = get_client_ip();
    $url = '/' . $request->module() . '/' . $request->controller() . '/' . $request->action();
    $msg = '[ ' . date('c') . ' ] ' . $ip . ' ' . $url . PHP_EOL . $msg . PHP_EOL;

    if (file_exists($baseDir)) {
        file_put_contents($baseDir, $msg, FILE_APPEND);
    } else {
        file_put_contents($baseDir, $msg);
    }
}

/**
 * 获取中文字符串指定长度内容
 * @param string $str       字符串
 * @param int $str_length   截取长度
 * @param string $hide_str  默认多余隐藏样式
 * @param string $unicode   字符集
 * @return string
 */
function get_zh_string($str = '', $str_length = 0, $hide_str = '...', $unicode = 'utf-8')
{
    $str_len = mb_strlen($str, $unicode);
    if ($str_len < $str_length) {
        return $str;
    }
    return mb_substr($str, 0, $str_length, $unicode) . $hide_str;
}

/**
 * 校验URL是否是https，默认是当前URL地址
 * @param  string  $url URL地址
 * @return boolean
 */
function is_ssl($url = '')
{
    if (!empty($url)) {
        if (stripos($url, 'https://') !== false) return true;
    } else {
        if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
            return true;
        } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
            return true;
        }
    }
    
    return false;
}

/**
 * 是否手机端访问
 * @return bool
 */
function is_mobile_client()
{
    $is_mobile = \util\Verify::isMobileClient();
    return $is_mobile;
}